import pymysql


#引用加密依赖
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization


import hashlib


#封装好的一个mysql框架
#我称他Asql
#自带秘钥加密方法 encode 加密 decode 解密
class Asql:
    __user = "root"
    __pass = "123456"
    __database = "tiecode"
    __host = "localhost"

    def __init__(self):
        #连接数据库
        self.conn = pymysql.connect(host=self.__host, user=self.__user, password=self.__pass, database=self.__database)
        #获取游标
        self.cursor = self.conn.cursor()

    def getCursor(self):
        # 获取游标
        self.cursor = self.conn.cursor()

    def close(self):
        # 关闭游标
        self.cursor.close()
        # 关闭数据库连接
        self.conn.close()

    #查询表中数据
    #conditions 查询条件
    def SelectAll(self,table:str,conditions:str=""):
        condition = ""
        if conditions != "":
            condition = " where " + conditions
        # 查询表中所有数据
        sql = f"select * from {table}{condition}"
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    #删除表中数据
    def DelData(self,table:str,conditions:str = ""):
        condition = ""
        if conditions != "":
            condition = " where " + conditions
        # 删除表中所有数据
        sql = f"delete from {table}{condition}"
        line = self.cursor.execute(sql)
        self.conn.commit()
        return line!=0

    #修改数据
    #最重要的是updateDate 是一个字典 键和键值和mysql语句相对应
    def Update(self,table:str,updateDate:{},conditions:str = ""):
        condition = ""
        if conditions != "":
            condition = " where " + conditions
        # 修改表中所有数据
        sql = f"update {table} set "
        for key in updateDate:
            sql += f"{key}=%s,"
        sql = sql[:-1]
        sql += condition
        line = self.cursor.execute(sql,tuple(updateDate.values()))
        self.conn.commit()
        return line!=0
    
    def Insert(self, table:str, data:{}):
        columns = ", ".join(data.keys())
        placeholders = ", ".join(["%s"] * len(data))
        # 插入数据
        try:
            sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
            values = tuple(data.values())
            line = self.cursor.execute(sql, values)
            self.conn.commit()
            return line != 0
        except Exception as e:
            return False

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def md5(self,str):
        md5 = hashlib.md5()
        md5.update(str.encode('utf-8'))
        return md5.hexdigest()


if __name__ == "__main__":
    sql = Asql()
    print(sql.Insert("text",{
        "uid":"100886",
        "title":"测试",
        "content":"测试",
        "time":"测试"
    }))